﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace KeyboardRemapper
{
   public partial class KeyTextBox : UserControl
   {
      List<int> m_lKeys = new List<int>();
      private bool m_bMultiKey;
      private int m_iDevice;

      [Browsable(false)]
      public int pDevice 
      {
         get
         {
            return m_iDevice;
         }
         set 
         {
            m_iDevice = value;
            UpdateText();
         }
      }

      [Browsable(false)]
      public List<int> pKeys
      {
         get { return m_lKeys; }
         set
         {
            m_lKeys = value;
            UpdateText();
         }
      }

      [Browsable(false)]
      public int MaximalKeyCount { get; set; }

      public KeyTextBox()
      {
         InitializeComponent();
         txtInput.GotFocus += new EventHandler(txtInput_GotFocus);
         txtInput.LostFocus += new EventHandler(txtInput_LostFocus);
         MaximalKeyCount = 3;
      }

      void txtInput_GotFocus(object sender, EventArgs e)
      {
         KeyInterceptor.DisableKeyboard();
         KeyInterceptor.KeyEvent += new KeyInterceptor.KeyEventDelegate(KeyInterceptor_KeyEvent);
      }

      void KeyInterceptor_KeyEvent(int code, int device, bool bKeydown)
      {
         if (bKeydown)
         {
            if (MultiKey)
            {
               if (m_lKeys.Count >= MaximalKeyCount)
                  m_lKeys.Clear();
               m_lKeys.Add(code);
            }
            else
            {
               m_lKeys.Clear();
               pDevice = device;
               m_lKeys.Add(code);
            }
            UpdateText();
         }
      }

      private void UpdateText()
      {
         if (MultiKey)
            txtInput.Text = string.Join(" + ", m_lKeys);
         else
         {
            if (pDevice != -1)
               txtInput.Text = "[" + pDevice + "] " + string.Join(" + ", m_lKeys);
            else
               txtInput.Text = string.Join(" + ", m_lKeys);
         }
      }


      void txtInput_LostFocus(object sender, EventArgs e)
      {
         KeyInterceptor.KeyEvent -= new KeyInterceptor.KeyEventDelegate(KeyInterceptor_KeyEvent);
         KeyInterceptor.EnableKeyboard();
      }


      public bool MultiKey
      {
         get
         {
            return m_bMultiKey;
         }
         set
         {
            m_bMultiKey = value;
            btnClear.Enabled = m_bMultiKey;
         }
      }

      private void btnClear_Click(object sender, EventArgs e)
      {
         m_lKeys.Clear();
         txtInput.Text = "";
         txtInput.Focus();
      }
   }
}
